//
//  HomeViewController.swift
//  swfitTest
//
//  Created by hncy on 2021/12/27.
//

import UIKit
import Alamofire
import MJRefresh
import FSPagerView
import Kingfisher


let cellId = "cellId"
let bannerId = "bannerId"
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, FSPagerViewDelegate, FSPagerViewDataSource {
  
    
    struct BaseEmptyParameter: Encodable {
        
    }
    
    var items: [HomeModel]?
    var tableView: UITableView!
    var bannerUrls:Array<Any>?
    
    
    lazy var pagerView: FSPagerView = {
        let pagerView = FSPagerView()
        pagerView.delegate = self
        pagerView.dataSource = self
        pagerView.automaticSlidingInterval = 3
        pagerView.isInfinite = !pagerView.isInfinite
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: bannerId)
        pagerView.transformer = FSPagerViewTransformer(type: .crossFading)
        return pagerView
    }()
    
    // 懒加载滚动图片浏下标
    lazy var pagerControl:FSPageControl = {
        let pageControl = FSPageControl()
        //设置下标的个数
        pageControl.numberOfPages = bannerUrls?.count ?? 0
        //设置下标位置
        pageControl.contentHorizontalAlignment = .center
        //设置下标指示器边框颜色（选中状态和普通状态）
        pageControl.setStrokeColor(.lightGray, for: .normal)
        pageControl.setStrokeColor(.darkGray, for: .selected)
        //设置下标指示器颜色（选中状态和普通状态）
        pageControl.setFillColor(.lightGray, for: .normal)
        pageControl.setFillColor(.darkGray, for: .selected)
        
        //设置下标指示器图片（选中状态和普通状态）
        //pageControl.setImage(UIImage.init(named: "1"), for: .normal)
        //pageControl.setImage(UIImage.init(named: "2"), for: .selected)
        
        //绘制下标指示器的形状 (roundedRect绘制绘制圆角或者圆形)
//        pageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 8, width: 8, height: 5),cornerRadius: 4.0), for: .normal)
        
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 6, height: 6)), for: .normal)
        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 6, height: 6)), for: .selected)
        return pageControl

    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
//        self.navigationController?.navigationItem.title="首页"   self.title = "首页"
        self.tabBarController?.navigationItem.title = "首页"
        self.tabBarController!.tabBar.tintColor = UIColor.hex(0xFBD005)
        bannerUrls = ["https://vkceyugu.cdn.bspapp.com/VKCEYUGU-9a31f973-1b6c-4def-b85e-3ec3b80f5c64/11c99d50-607b-4755-b85a-d88a7014d807.png",
                     "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-9a31f973-1b6c-4def-b85e-3ec3b80f5c64/24f9fb25-455d-4b94-8839-a0a90523e0e0.png",
                     "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-9a31f973-1b6c-4def-b85e-3ec3b80f5c64/a20a2bab-277f-4a1f-9bc6-018a1470f146.png",
                     ]
        
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        // 注册cell
        tableView.register(HomeCell.self, forCellReuseIdentifier: cellId)
        //上下拉刷新
        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(HomeViewController.headerRefresh))
        self.tableView.mj_header = header
        // 上拉刷新
        let footer = MJRefreshAutoNormalFooter()
        footer.setRefreshingTarget(self, refreshingAction: #selector(HomeViewController.footerRefresh))
        self.tableView.mj_footer = footer
        self.tableView.mj_footer.isHidden = true
        
        // 顶部banner
        let headerView = HomeHeaderView(frame: CGRect(x: 0, y: 0, width: view.mj_w, height: 200) )
        headerView.addSubview(pagerView)
        pagerView.frame = headerView.bounds
        
        headerView.addSubview(pagerControl)
        pagerControl.frame = CGRect(x: headerView.mj_w-100, y: 170, width: 100, height: 30)
        
        
        tableView.tableHeaderView = headerView
        
        // 获取数据
        self.tableView.mj_header.beginRefreshing()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.tabBarController?.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabBarController?.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    // 顶部刷新
    @objc func headerRefresh() {
      getList()
      print("下拉刷新")
        
    }
    // 底部刷新
    @objc func footerRefresh(){
      print("上拉刷新")
    }
    
    func getList() {
        AF.request("https://cnodejs.org/api/v1/topics", method: .get, parameters: BaseEmptyParameter(), encoder: URLEncodedFormParameterEncoder(encoder: URLEncodedFormEncoder(), destination: .methodDependent), headers: nil, interceptor: nil, requestModifier: nil).response { response in
 
            // data to jsonstring
            let jsonString = String(bytes: response.data!, encoding: String.Encoding.utf8)
             
            if let models =  [HomeModel].deserialize(from: jsonString, designatedPath: "data") {
                
                self.items = (models as! [HomeModel])
                self.tableView.reloadData()
                self.tableView.mj_header.endRefreshing()
            }
        }
    }
    
    // tableView delegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! HomeCell
        
        cell.titleLab.text = items?[indexPath.row].title
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UIUtils.pushViewController(parent: self, vc: DetailViewController(id: (items?[indexPath.row].id)!))
    }
    
    // banner delegate
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannerUrls?.count ?? 0
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: bannerId, at: index)
        if let url = URL(string: bannerUrls?[index % (bannerUrls?.count ?? 1)] as! String ?? "" ) {
            cell.imageView!.kf.setImage(with: url)
        }
        
        return cell
    }
    func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int) {
        self.pagerControl.currentPage = index
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        self.navigationController?.pushViewController(TestViewController(), animated: true)
//        UIUtils.pushViewController(parent: self, vc: TestViewController())
    }
}
